Write a Rust program to find the second smallest element in an array.
Write a Rust program to find the second smallest element in an array.
588
22-Jun-2023
Aryan Kumar
23-Jun-2023Sure, here is a Rust program to find the second smallest element in an array:
Rust
This program first defines a function called find_second_smallest that takes an array of i32 numbers as input and returns the second smallest element in the array. The function first initializes two variables, smallest and second_smallest, to the first two elements in the array. Then, the function iterates through the array, comparing each element to smallest and second_smallest. If an element is smaller than smallest, then second_smallest is assigned the value of smallest and smallest is assigned the value of the element. If an element is smaller than second_smallest but not smaller than smallest, then second_smallest is assigned the value of the element.
The main function of the program then calls the find_second_smallest function with the array [10, 5, 2, 7, 3, 1, 9, 8, 6] as input. The result of the function call is then printed to the console.
To run the program, you can save it as a file called find_second_smallest.rs and then compile it using the following command:
Code snippet
Once the program is compiled, you can run it using the following command:
Code snippet
This will print the following output to the console:
Code snippet